package com.wgchao.authmanager;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.List;

/**
 * @作者：wgchao
 * @时间：21:22 2019/8/22 0022
 * @用途：跨域访问
 **/
@Configuration
public class GlobalCorsConfig {
    List<String> allowedHeaders = Arrays.asList("authorization", "accessToken","content-type", "X-Requested-With", "XMLHttpRequest");
    List<String> exposedHeaders = Arrays.asList("authorization", "accessToken", "content-type", "X-Requested-With", "XMLHttpRequest");
    List<String> allowedMethods = Arrays.asList("POST", "GET", "DELETE", "PUT", "OPTIONS");
    List<String> allowedOrigins = Arrays.asList("*");
    @Bean
    public CorsFilter corsFilter() {
        //1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //放行哪些原始域
        config.setAllowedOrigins(allowedOrigins);
        //是否发送Cookie信息
        config.setAllowCredentials(true);
        //放行哪些原始域(请求方式)
        config.setAllowedMethods(allowedMethods);
        //放行哪些原始域(头部信息)
        config.setAllowedHeaders(allowedHeaders);
        //暴露哪些头部信息（因为跨域访问默认不能获取全部头部信息）
        config.setExposedHeaders(exposedHeaders);

        //2.添加映射路径
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }
}
